package no.saiboten.tourbuilder.tournament.controller;

import no.saiboten.tourbuilder.tournament.service.TournamentService;
import no.saiboten.tourbuilder.user.UserDAO;
import no.saiboten.tourbuilder.user.UserStatus;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

@Controller
@RequestMapping("/tournament")
public class TournamentController {

	UserDAO userDAO;

	TournamentService tournamentService;

	UserStatus userStatus;

	@Autowired
	public TournamentController(UserDAO userDAO,
			TournamentService tournamentService, UserStatus userStatus) {
		this.userDAO = userDAO;
		this.tournamentService = tournamentService;
		this.userStatus = userStatus;
	}

	@RequestMapping("")
	public ModelAndView findAllTournaments() {
		ModelAndView mav = new ModelAndView("tournament/view_tournaments");
		mav.addObject("tournaments", tournamentService.findAllTournaments());
		return mav;
	}

	@RequestMapping("/get/{tournamentid}")
	public ModelAndView findTournament(@PathVariable String tournamentid) {
		ModelAndView mav = new ModelAndView("tournament/view_tournament");
		mav.addObject("tournament",
				tournamentService.getTournament(tournamentid));
		return mav;
	}

	@RequestMapping("/join/{tournamentid}")
	public ModelAndView addUserToTournament(@PathVariable String tournamentid) {

		RedirectView redirectView = new RedirectView("/tourbuilder/login/login");

		if (userStatus.isAuthenticated()) {
			if (tournamentService.addUserToTournament(
					userStatus.getUser(), tournamentid)) {
				redirectView = new RedirectView("/tourbuilder/tournament/get/"
						+ tournamentid);
				return new ModelAndView(redirectView);
			} else {
				ModelAndView mav = new ModelAndView(
						"tournament/view_tournaments");
				mav.addObject("result", "Turneringen er full!");
				return mav;
			}
		}

		return new ModelAndView(redirectView);
	}
}
